public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

// 迭代法：重复执行比较大小的代码，遍历完两个链表
class MySolution2 {
    ListNode prehead = new ListNode(0);
    ListNode tail = prehead;
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        while (list1 != null && list2 != null) {
            if (list1.val >= list2.val) {
                tail.next = list2;
                list2 = list2.next;
            } else if (list1.val < list2.val) {
                tail.next = list1;
                list1 = list1.next;
            }
            tail = tail.next;
        }
        tail.next = list1 != null ? list1 : list2;
        return prehead.next;
    }
}

// 迭代
class Solution2 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode prehead = new ListNode(-1);
        ListNode cursor = prehead;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cursor.next = l1;
                l1 = l1.next;
            } else {
                cursor.next = l2;
                l2 = l2.next;
            }
            cursor = cursor.next;
        }

        // 合并后 l1 和 l2 最多只有一个还未被合并完，我们直接将 链表末尾 指向 未合并完的 链表 即可
        cursor.next = l1 == null ? l2 : l1;

        return prehead.next;
    }
}

// 递归
class MySolution1 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        } else {
            if (list1.val <= list2.val) {
                list1.next = mergeTwoLists(list1.next, list2);
                return list1;
            } else {
                list2.next = mergeTwoLists(list1, list2.next);
                return list2;
            }
        }
    }
}

// 递归
class Solution1 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}